package com.fancy.learncenter.activity;

import android.app.Dialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.PagerSnapHelper;
import android.support.v7.widget.RecyclerView;
import android.view.WindowManager;

import com.fancy.learncenter.activity.base.BaseActivity;
import com.fancy.learncenter.adapter.PicDetailAdapter;
import com.fancy.learncenter.bean.BaseDataBean;
import com.fancy.learncenter.bean.PicSavaDataBean;
import com.fancy.learncenter.net.HttpMehtod;
import com.fancy.learncenter.net.IdeaObserver;
import com.fancy.learncenter.utils.ToastUtil;
import com.fancy.learncenter.utils.Utils;
import com.fancy.learncenter.view.CustomProgressDialog;
import com.superservice.lya.R;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import okhttp3.ResponseBody;
import retrofit2.http.HTTP;

public class GalleryPicDetailActivity extends BaseActivity {


    public static String PIC_KEY = "PIC_KEY";
    public static String PIC_POSITION_KEY = "PIC_POSITION_KEY";
    public static String PIC_SAVA_KEY = "PIC_SAVA_KEY";

    @Bind(R.id.recycleView)
    RecyclerView recycleView;

    PicDetailAdapter picDetailAdapter;
    ArrayList<String> itemDatas;
    int position = 0;

    boolean isSava = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_gallery_pic_detail, Status.STATUS);
        ButterKnife.bind(this);


        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);// 设置全屏

        itemDatas = getIntent().getStringArrayListExtra(PIC_KEY);
        position = getIntent().getIntExtra(PIC_POSITION_KEY, 0);
        isSava = getIntent().getBooleanExtra(PIC_SAVA_KEY, true);

        ArrayList<PicSavaDataBean> datas = new ArrayList<>();
        for (int i = 0; i < itemDatas.size(); i++) {
            PicSavaDataBean picSavaDataBean = new PicSavaDataBean();

            picSavaDataBean.setImgUrl(itemDatas.get(i));

            datas.add(picSavaDataBean);
        }
        picDetailAdapter = new PicDetailAdapter(this, datas, isSava);
        picDetailAdapter.setSavaCallBack(new PicDetailAdapter.SavaCallBack() {
            @Override
            public void saveCallBack(int position) {
                curSava = position;
                savaImg(picDetailAdapter.itemDatas.get(position).getImgUrl());
            }
        });

        linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        recycleView.setLayoutManager(linearLayoutManager);

        new PagerSnapHelper().attachToRecyclerView(recycleView);

        recycleView.setAdapter(picDetailAdapter);

        Utils.MoveToPosition(linearLayoutManager, recycleView, position);


        dialog = CustomProgressDialog.creatRequestDialog(this);
    }

    LinearLayoutManager linearLayoutManager;

    @OnClick(R.id.back_icon)
    public void onViewClicked() {
        finish();
    }

    Dialog dialog;
    Bitmap bitmap;

    @Override
    public void finish() {
        super.finish();
        if (bitmap != null) {
            bitmap.recycle();
        }

        if (dialog.isShowing()) {
            dialog.dismiss();
        }

    }

    public void savaImg(String str) {

        HttpMehtod.getInstance().downImg(str, new Observer<ResponseBody>() {
            @Override
            public void onSubscribe(Disposable d) {
                dialog.show();
            }

            @Override
            public void onNext(ResponseBody value) {
                dialog.dismiss();
                byte[] bys = new byte[0];
                try {
                    bys = value.bytes(); //注意：把byte[]转换为bitmap时，也是耗时操作，也必须在子线程
                    bitmap = BitmapFactory.decodeByteArray(bys, 0, bys.length);
                    runOnUiThread(new Runnable() {//开启主线程更新UI
                        @Override
                        public void run() {

                            try {//调用saveFile方法
                                saveImageToGallery(bitmap);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    });

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }


            @Override
            public void onError(Throwable e) {
                dialog.dismiss();
            }

            @Override
            public void onComplete() {

            }
        });
    }

    int curSava = 0;

    public void saveImageToGallery(Bitmap bmp) {
        // 首先保存图片
        String fileName = Utils.getPicRootPath() + System.currentTimeMillis() + ".jpg";
        File file = new File(fileName);
        try {
            FileOutputStream fos = new FileOutputStream(file);
            bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();

            picDetailAdapter.itemDatas.get(curSava).setSava(true);

            picDetailAdapter.notifyDataSetChanged();

            ToastUtil.show("图片已保存至 /LinYa文件下");

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
